import {ref, reactive} from "vue";
import {ElMessage} from "element-plus";
import {usePagination} from "./usePagination";
import instance from "@/api/request";

async function fetchUserList(params) {
    return new Promise((resolve) => {
        try {
            instance.post("/system/user/list", params).then((res) => {
                resolve(res.data);
            });
        } catch (error) {
            ElMessage.error("加载失败");
        }
    });
}

async function fetchUserUpdate(user) {
    return new Promise((resolve) => {
        try {
            instance.put("/system/user/status_update", user).then((res) => {
                resolve(res.data);
            });
        } catch (error) {
            ElMessage.error("加载失败");
        }
    });
}

export function useUserManagement() {
    // 1. 查询参数
    const queryParams = reactive({
        username: "",
        status: null,
        gender: null,
        delFlag: 0,
        roleCodes: [],
    });

    // 2. 使用通用分页 Hook
    const {current, size, total} =
        usePagination(10);

    // 3. 列表数据
    const userList = ref([]);
    const loading = ref(false);

    // 4. 加载数据
    const loadData = async () => {
        loading.value = true;
        try {
            const res = await fetchUserList({
                current: current.value,
                size: size.value,
                ...queryParams,
            });
            userList.value = res.records;
            total.value = res.total;
        } catch (err) {
            ElMessage.error("加载失败");
        } finally {
            loading.value = false;
        }
    };

    // 5. 搜索
    const search = async () => {
        current.value = 1
        await loadData();
    };

    // 6. 重置
    const reset = () => {
        queryParams.username = "";
        queryParams.status = null;
        queryParams.roleId = null;
        search();
    };

    // 7. 刷新
    const refresh = () => {
        loadData();
        ElMessage.success("刷新成功");
    };

    // 8. 分页事件
    const handleCurrentChange = (newPage) => {
        current.value = newPage
        loadData();
    };

    const handleSizeChange = (newSize) => {
        size.value = newSize
        loadData();
    };

    return {
        // 数据
        queryParams,
        userList,
        loading,
        current,
        size,
        total,

        // 方法
        search,
        reset,
        refresh,
        handleCurrentChange,
        handleSizeChange,
        fetchUserUpdate
    };
}
